<template>
  <PlayGround v-if="$store.state.pk.status === 'playing'" />
  <MatchView v-if="$store.state.pk.status === 'matching'" />
  <ResultView v-if="$store.state.pk.loser !== 'none'"></ResultView>

  <div
    v-if="
      $store.state.pk.status === 'playing' &&
      $store.state.user.info.id === $store.state.pk.a_id
    "
    class="tgs"
  >
    左下角
  </div>
  <div
    v-if="
      $store.state.pk.status === 'playing' &&
      $store.state.user.info.id === $store.state.pk.b_id
    "
    class="tgs"
  >
    右上角
  </div>
</template>

<script>
import PlayGround from "@/components/PlayGround";
import MatchView from "@/views/pk/MatchView";
import ResultView from "@/components/ResultView";
import { useStore } from "vuex";
import { onMounted, onUnmounted } from "@vue/runtime-core";
export default {
  name: "PkView",
  components: {
    PlayGround,
    MatchView,
    ResultView,
  },

  setup() {
    const store = useStore();
    const access = store.state.user.info.access;
    const socketURL = store.state.web.webAddress+ `/websocket/${access}`;
    let socket = null;

    store.commit("updateLoser", "none");
    store.commit("updateIsRecord", false);

    onMounted(() => {
      socket = new WebSocket(socketURL);

      store.commit("updateOpponent", {
        username: "我的对手",
      });

      socket.onopen = () => {
        store.commit("updateSocket", socket);
      };

      socket.onmessage = (msg) => {
        const data = JSON.parse(msg.data);
        if (data.event === "start-matching") {
          store.commit("updateOpponent", {
            username: data.username,
            avatar: data.avatar,
          });
          setTimeout(() => {
            store.commit("updateStatus", "playing");
          }, 200);
          store.commit("updateGamemap", data.gamemap);

          store.commit("updateGame", data.respGame);
        } else if (data.event === "move") {
          const game = store.state.pk.gameObject;
          const [snake0, snake1] = game.snakes;
          snake0.set_derection(data.a_direction);
          snake1.set_derection(data.b_direction);
        } else if (data.event === "result") {
          const game = store.state.pk.gameObject;
          const [snake0, snake1] = game.snakes;
          if (data.loser === "all" || data.loser === "A") {
            snake0.status = "die";
          }
          if (data.loser === "all" || data.loser === "B") {
            snake1.status = "die";
          }
          store.commit("updateLoser", data.loser);
        }
      };

      socket.onclose = () => {
        console.log("disconnected!");
      };
    });

    onUnmounted(() => {
      socket.close();
      store.commit("updateStatus", "matching");
    });
  },
};
</script>

<style scoped>
div.tgs{
  font-size: 4rem;
  /* width: 600px; */
  color: white;
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>